package com.study.crypto.basic.signer;

import org.bouncycastle.jcajce.spec.SM2ParameterSpec;

import java.security.*;

/**
 * 使用 jdk API 进行 sm2 签名
 * @author Songjin
 * @since 2021-01-14 20:08
 */
public class JdkSM2Signer extends Signer {

    @Override
    public byte[] sign(byte[] inData, PrivateKey privateKey) throws GeneralSecurityException {
        SM2ParameterSpec parameterSpec = new SM2ParameterSpec(SM2_ID);
        Signature signer = Signature.getInstance(SIGN_ALGO_SM3_SM2, BC);
        signer.setParameter(parameterSpec);
        signer.initSign(privateKey, new SecureRandom());
        signer.update(inData);
        return signer.sign();
    }
    
    @Override
    public boolean verify(byte[] inData, byte[] signature, PublicKey publicKey) throws GeneralSecurityException {
        SM2ParameterSpec parameterSpec = new SM2ParameterSpec(SM2_ID);
        Signature verifier = Signature.getInstance(SIGN_ALGO_SM3_SM2, BC);
        verifier.setParameter(parameterSpec);
        verifier.initVerify(publicKey);
        verifier.update(inData);
        return verifier.verify(signature);
    }
}
